package ch.cn.hdmidemo;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.example.x6.serial.SerialPort;
import com.hisilicon.android.tvapi.SourceManager;
import com.hisilicon.android.tvapi.constant.EnumSourceIndex;
import com.hisilicon.android.tvapi.vo.RectInfo;
import com.monkey.miclockview.MiClockView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main2Activity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private VideoView myVideoView;
    private SourceManager mSourceManager;

    public static int width;
    public static int height;
    public static float density;
    public byte[] bytes = new byte[]{0x2e,0x08,0x32,0x73,0x04,0x05};
    public byte[] RequCmd = new byte[]{0x2e,0x08,0x32,0x73,0x04,0x05};
    private SerialPort serialttyS1;
    public InputStream ttyS1InputStream;
    public OutputStream ttyS1OutputStream;
    public boolean startflag=false;
    MiClockView miClockView;

    RelativeLayout rl_time;
    ImageView iv_needle_time;
    ImageView iv_needle_hour;
    ImageView iv_needle_minute;

    float degree;

    private long loopTime = 1000;  //时间显示间隔   默认100毫秒
    private boolean isThread = true;
    Thread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);

            setContentView(R.layout.activity_main_jinguan_310);

        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        density = metrics.density;
        width = metrics.widthPixels;
        height = metrics.heightPixels;
        Log.e("ma===onCreate", density+"==="+width+"==="+height);

        init_serial();

//        mSourceManager = HitvManager.getInstance().getSourceManager();
//        initHdmi(469,  0,  1920-469-512,  590);

//        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(512, 590);
//        params.setMargins(1920-512, 0, 512, 590);
//        miClockView = new MiClockView(this, R.drawable.clock_bg, R.drawable.needle_minute, R.drawable.needle_minute, R.drawable.needle_hour, R.drawable.center);
//        addContentView(miClockView, params);



        //屏保界面触摸事件，触摸界面就能关闭屏保界面，回到之前界面
//        miClockView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                Log.e("mcv===onTouch", "===");
//
//                miClockView.setVisibility(View.GONE);
//                return false;
//            }
//        });
//        rl_time = (RelativeLayout) findViewById(R.id.rl_time);
        iv_needle_time = (ImageView) findViewById(R.id.iv_needle_time);
        iv_needle_hour = (ImageView) findViewById(R.id.iv_needle_hour);
        iv_needle_minute = (ImageView) findViewById(R.id.iv_needle_minute);
        iv_needle_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                degree-=30;
                iv_needle_time.setPivotX(iv_needle_time.getWidth()/2);
//                iv_needle_time.setPivotY(iv_needle_time.getHeight());
                iv_needle_time.setPivotY(2);
                iv_needle_time.setRotation(degree);

                write(bytes);
            }
        });

        iv_needle_hour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                degree-=30;

//                iv_needle_hour.setPivotX(iv_needle_hour.getWidth()/2);
//                iv_needle_time.setPivotY(iv_needle_hour.getHeight());

                Log.e("iv_needle_hour===", "==="+iv_needle_hour.getHeight()/2);

                iv_needle_hour.setPivotX(17);
                iv_needle_hour.setPivotY(iv_needle_hour.getHeight()/2);
//                iv_needle_hour.setPivotY(0);
                iv_needle_hour.setRotation(degree);
            }
        });

        iv_needle_minute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                degree-=30;

                iv_needle_minute.setPivotX(iv_needle_minute.getWidth()/2);
//                iv_needle_time.setPivotY(iv_needle_minute.getHeight());
                iv_needle_minute.setPivotY(7);
                iv_needle_minute.setRotation(degree);
            }
        });


        isThread = true;
        loopRead();
    }
    protected void send(){
        Log.e("f333===", startflag+"==="+iv_needle_time.getWidth()+"==="+iv_needle_time.getHeight());

        if(!startflag){
            Log.e("f334232===", iv_needle_time.getWidth()+"==="+iv_needle_time.getHeight());
            startflag=true;
            write(RequCmd);
            loopTime=100;
            Log.e("f1===", iv_needle_time.getWidth()+"==="+iv_needle_time.getHeight());
        }else if(startflag){
            startflag=false;
              read(bytes); //TODO 串口获取车速
            Log.e("f2===", iv_needle_time.getWidth()+"==="+iv_needle_time.getHeight());
            loopTime=400;
        }
    }
    private void loopRead(){
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isThread){
                    m_myHandler.sendEmptyMessage(1);
                    try {
                        Thread.sleep(loopTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        thread.start();
    }
    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
//                case 0:
//                    rl_time.setVisibility(View.GONE);
//                    miClockView.setVisibility(View.GONE);
//                    break;

                case 1:
                  //  startflag=0;
                    //                    send();
                   read(bytes);
//                    miClockView.drawTimeText("123");
                    break;


                default:
                    break;
            }
            return false;
        }
    });

    /* 打开串口 */
    private void init_serial() {
        try {
            //serialttyS1 = new SerialPort(new File("/dev/ttyS1"),38400,0);
            serialttyS1 = new SerialPort(new File("/dev/ttyAMA2"),115200,0);
            ttyS1InputStream = serialttyS1.getInputStream();
            ttyS1OutputStream = serialttyS1.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void write(byte[] bytes){
        /* 串口发送字节 */
        try {
            ttyS1OutputStream.write(bytes, 0, bytes.length);
           // ttyS1OutputStream.write(bytes);   //TODO
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    byte[] read_buf = new byte[1024];
    public int read(byte[] bytes){
        /* 串口发送字节 */
        try {
            Log.e("read===", "===");
            read_buf = new byte[1024];
            int read_count = ttyS1InputStream.read(read_buf);   //TODO
//            int read_count = ttyS1InputStream.read(read_buf, 0, read_buf.length);
            Log.e("read===1", "==="+read_count);
            if (read_count < 0) {
                read_count = 0;
                return 0;
            }
            String value = CarUtil.toHex(read_buf, read_count);
            Log.e("jiangyunwei", "==="+value);
//            Log.e("jiangyunwei", read_buf[0]+"==="+read_buf[1]+"==="+read_buf[2]+"==="+read_buf[3]+"==="+read_buf[4]+"==="+read_buf[5]+"==="+read_buf[6]+"==="+read_buf[7]+"==="+value);
//            System.out.println(value);
            //Log.e("f2===", temp+"===");
           // "002e2606006000000000002e08061506090a25006102e0806"

//            miClockView.setMydate(value);
            if((read_buf[0]==0x2E)){
                switch(read_buf[1]){
                    case  0x08:
                        if(read_count==10){
                            Log.e("jiangyunwei", read_buf[0] + "===" + read_buf[1] + "===" + read_buf[2] + "===" + read_buf[3] + "===" + read_buf[4] + "===" + read_buf[5] + "===" + read_buf[6] + "===" + read_buf[7] + "===" + value);
                            miClockView.setHour(read_buf[6]);
                            miClockView.setMinute(read_buf[7]);
                            miClockView.setMydate("20" + read_buf[3] + "-" + (read_buf[4] < 10 ? ("0" + read_buf[4]) : read_buf[4]) + "-" + (read_buf[5] < 10 ? ("0" + read_buf[5]) : read_buf[5]));
                        }
                    break;

                    case  0x26:
                        if(read_count==10) {
                            Log.e("jiangyunwei", read_buf[0] + "===" + read_buf[1] + "===" + read_buf[2] + "===" + read_buf[3] + "===" + read_buf[4] + "===" + value);
                            int degree = read_buf[3];
                            int degree2 = read_buf[4];
                            iv_needle_time.setPivotX(iv_needle_time.getWidth() / 2);
                            iv_needle_time.setPivotY(2);//支点在图片中心  22:中心偏移量
                            iv_needle_time.setRotation(degree * 16 + degree2); //-120:起始角度
                        }
                    break;

                    case 0x09:
                        if (read_count ==5) {
                            Log.e("jiangyunwei", rl_time+ "===" +miClockView+ "===" +read_buf[0] + "===" + read_buf[1] + "===" + read_buf[2] + "===" + read_buf[3] + "===" + value);

                            m_myHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (read_buf[3] == 1) {
                                        rl_time.setVisibility(View.VISIBLE);
                                        miClockView.setVisibility(View.VISIBLE);
                                    } else {
                                        rl_time.setVisibility(View.GONE);
                                        miClockView.setVisibility(View.GONE);
                                    }
                                }
                            });

                        }
                    break;

                }

            }
        } catch (Exception e) {
            Log.e("f2===e", e+"===");

            e.printStackTrace();
        }
        return 1;
    }

    private void initHdmi(final int hlocationX, final int hlocationY, final int width, final int height) {

        myVideoView = findViewById(R.id.mvideoview);
        myVideoView.post(new Runnable() {
            @Override
            public void run() {
                int location[] = new int[2];
                //int width;
                //int height;
                myVideoView.getLocationOnScreen(location);
               Log.e(TAG, "initHdmi: myVideoView.getX() = " + location[0]);
                Log.e(TAG, "initHdmi: myVideoView.getY() = " + location[1]);
                Log.e(TAG, "initHdmi: myVideoView.getWidth() = " + myVideoView.getWidth());
                Log.e(TAG, "initHdmi: myVideoView.getHeight() = " + myVideoView.getHeight());
                //width = myVideoView.getWidth();
               // height = myVideoView.getHeight();
                reviseXyForHdmi(hlocationX ,hlocationY, width, height);
            }
        });
//        mSourceManager = HitvManager.getInstance().getSourceManager();
        if (true) {
            mSourceManager.deselectSource(EnumSourceIndex.SOURCE_MEDIA, true);
            mSourceManager.selectSource(EnumSourceIndex.SOURCE_HDMI3, 0);
        }

    }

    private boolean reviseXyForHdmi(int locationX, int locationY, int width, int height) {

        //int x = locationX;
        //int y = locationY;
      //  int w = width;
       // int h = height;
       /*
        switch (angle) {
            case 0:
                break;
            case 90:
                locationX = 1920 - (y + h);
                locationY = x;
                width = h;
                height = w;
                break;
            case 180:
                locationX = 1920 - (x + w);
                locationY = 1080 - (y + h);
                break;
            case 270:
                locationX = y;
                locationY = 1080 - (x + w);
                width = h;
                height = w;
                break;
            default:
                return false;
        }*/
        Log.e(TAG, "reviseXyForHdmi: locationX = " + locationX);
        Log.e(TAG, "reviseXyForHdmi: locationY = " + locationY);
        Log.e(TAG, "reviseXyForHdmi: width = " + width);
        Log.e(TAG, "reviseXyForHdmi: height = " + height);

        mSourceManager.setWindowRect(new SmallScreenRectInfo(locationX, locationY, width, height), 0);

        return true;
    }
    @Override
   protected void onDestroy() {
        super.onDestroy();
//        mSourceManager.deselectSource(EnumSourceIndex.SOURCE_HDMI3, true);
//        mSourceManager.selectSource(EnumSourceIndex.SOURCE_MEDIA, 0);
//        if (myVideoView != null) {
//            myVideoView.suspend();
//        }
   }
    class SmallScreenRectInfo extends RectInfo {
        public SmallScreenRectInfo(int x, int y, int width, int height) {
            setX(x);
            setY(y);
            setW(width);
            setH(height);
        }
    }
}